//
//  ByClassViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "ByClassViewController.h"
#import "AppDelegate.h"
#import "ByClassTableViewCell.h"
#import "ByClassData.h"
#import "SubCat.h"
#import "ByClassCollectionViewCell.h"
#import "ClassContentViewController.h"
#import "SearchViewController.h"

@interface ByClassViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UITableView *tableV;
@property (nonatomic, strong) NSMutableArray *leftArr;
@property (nonatomic, strong) UICollectionView *collectionV;
@property (nonatomic, strong) NSMutableArray *rightArr;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) NSString *selectName;

@end

@implementation ByClassViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    // tabBar现身
    self.tabBarController.tabBar.hidden = NO;
    // 侧边栏手势开启
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appD.leftSlideVC setPanEnabled:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self dataHandler];
    self.title = @"分类";
    
//    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(pushSearchVCAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(leftAction)];
    
    // 侧边栏按钮
    UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtn.frame = CGRectMake(0, 0, 20, 18);
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"drawer"] forState:UIControlStateNormal];
    [menuBtn addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuBtn];
    
    // 左侧tableView
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 120, Screenheight) style:UITableViewStylePlain];
    _tableV.delegate = self;
    _tableV.dataSource = self;
    [self.view addSubview:_tableV];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.bounces = NO;
    _tableV.backgroundColor = [UIColor clearColor];
    
    // 右侧collectionView
    UICollectionViewFlowLayout *flowL = [[UICollectionViewFlowLayout alloc] init];
    flowL.itemSize = CGSizeMake((ScreenWidth - 140) / 3, (ScreenWidth - 140) / 3);
    flowL.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    flowL.minimumInteritemSpacing = 5;
    flowL.minimumLineSpacing = 5;
    
    self.collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(120, 64, ScreenWidth - 120, Screenheight - 64 - 49) collectionViewLayout:flowL];
    _collectionV.delegate = self;
    _collectionV.dataSource = self;
    [self.view addSubview:_collectionV];
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
            _collectionV.backgroundColor = [UIColor colorWithRed:57/255.0 green:57/255.0 blue:57/255.0 alpha:1];
    }else{
        _collectionV.backgroundColor = [UIColor whiteColor];
    }
    _collectionV.bounces = YES;
    _collectionV.showsVerticalScrollIndicator = NO;
    [_collectionV registerClass:[ByClassCollectionViewCell class] forCellWithReuseIdentifier:@"rightitem"];
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    _HUD.labelText = @"数据加载中...";
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(nightAction:) name:@"night" object:nil];
    
}

- (void)nightAction:(NSNotification *)sender
{
    [[NightLabel appearance]setTextColor:[sender.userInfo objectForKey:@"textcolor"]];
    self.collectionV.backgroundColor = [sender.userInfo objectForKey:@"backcolor"];
    self.tableV.backgroundColor = [sender.userInfo objectForKey:@"backcolor"];
    [self.tableV reloadData];
    [self.collectionV reloadData];
}

// 推出搜索页
- (void)pushSearchVCAction:(UIBarButtonItem *)bBtn
{
    self.tabBarController.tabBar.hidden = YES;
    SearchViewController *searcgaVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searcgaVC animated:YES];
    
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appD.leftSlideVC setPanEnabled:NO];
    
}

// 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SubCat *selectS = [self.rightArr objectAtIndex:indexPath.item];
    ClassContentViewController *classCVC = [[ClassContentViewController alloc] init];
    classCVC.pinyin = selectS.pinyin;
    classCVC.titleNavi = selectS.cat_name;
    NSLog(@"%@", classCVC.pinyin);
    [self.navigationController pushViewController:classCVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appD.leftSlideVC setPanEnabled:NO];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.rightArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ByClassCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"rightitem" forIndexPath:indexPath];
    
    SubCat *nowS = [_rightArr objectAtIndex:indexPath.item];
//    NSLog(@"lala  %@", nowS.imageC);
    [cell.imageV sd_setImageWithURL:nowS.imageC];
    cell.name.text = nowS.cat_name;
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
        cell.name.textColor = [UIColor whiteColor];
    }else{
        cell.name.textColor = [UIColor blackColor];
    }
    
    return cell;
}

// 左点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ByClassTableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];
    
    // 把点击的cell名取出来
    self.selectName = selectCell.nameL.text;
    
    // 遍历所有的cell名,如果cell名等于刚才取出的,给红色
    for (ByClassTableViewCell *cell in tableView.visibleCells)
    {
        cell.nameL.textColor = [UIColor blackColor];
        cell.redV.hidden = YES;
        
        if ([cell.nameL.text isEqualToString:self.selectName]) {
            
            cell.nameL.textColor = [UIColor redColor];
            cell.redV.hidden = NO;
        }else
        {
            if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
                cell.nameL.textColor = [UIColor whiteColor];
            }else{
            cell.nameL.textColor = [UIColor blackColor];
            }
            cell.redV.hidden = YES;
        }
    }

    // 取出点击的数据里的数组
    ByClassData *nowBCD = [self.leftArr objectAtIndex:indexPath.row];
    self.rightArr = nowBCD.subCatArr;
    [self.collectionV reloadData];

    
}

// 防止从用, 每次滚动都把字体红色从给一遍
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    for (ByClassTableViewCell *cell in self.tableV.visibleCells)
    {
        cell.nameL.textColor = [UIColor blackColor];
        cell.redV.hidden = YES;
        
        if ([cell.nameL.text isEqualToString:self.selectName]) {
            
            cell.nameL.textColor = [UIColor redColor];
            cell.redV.hidden = NO;
        }else
        {
            if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
                cell.nameL.textColor = [UIColor whiteColor];
            }else{
            cell.nameL.textColor = [UIColor blackColor];
            }
            cell.redV.hidden = YES;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _leftArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ByClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftcell"];
    
    if (!cell) {
        cell = [[ByClassTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"leftcell"];
    }
    
    ByClassData *classD = [self.leftArr objectAtIndex:indexPath.row];
    cell.nameL.text = classD.name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.tag = indexPath.row + 100;
//    if (indexPath.row == 0) {
//        cell.nameL.textColor = [UIColor redColor];
//        cell.redV.hidden = NO;
//    }
    
    return cell;
}

// 侧边栏动作
- (void)leftAction
{
    
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appD.leftSlideVC.closed) {
        [appD.leftSlideVC openLeftView];
    }else{
        [appD.leftSlideVC closeLeftView];
    }
    
}

- (void)dataHandler
{
    
    [AFRequdstAndLoad dataURLStr:@"http://www.meilele.com/solr_api/solr-manage/catalog/" datahand:^(id object) {
        
        if (object) {
            [_HUD removeFromSuperview];
        }
        // 把所有并列的数组拼接到一个数组里
        self.rightArr = [NSMutableArray array];
        self.leftArr = [NSMutableArray array];
        
        NSDictionary *rootDic = [object objectForKey:@"categorySortMap"];
        NSArray *jiajuArr = [rootDic objectForKey:@"jiaju"];
        
        for (NSDictionary *jiajuDic in jiajuArr) {
            ByClassData *classD = [[ByClassData alloc] init];
            NSDictionary *parentCatDic = [jiajuDic objectForKey:@"parentCat"];
            classD.name = [parentCatDic objectForKey:@"cat_name"];
            classD.subCatArr = [NSMutableArray array];
            NSArray *subCatArr = [jiajuDic objectForKey:@"subCatList"];
            // ByClassData类里的数组装SubCat类
            for (NSDictionary *dic in subCatArr) {
                SubCat *subCat = [[SubCat alloc] init];
                [subCat setValuesForKeysWithDictionary:dic];
                [classD.subCatArr addObject:subCat];
            }
            [self.leftArr addObject:classD];
        }
        
        NSArray *jiancaiArr = [rootDic objectForKey:@"jiancai"];

        for (NSDictionary *jiancaiDic in jiancaiArr) {
            ByClassData *classD = [[ByClassData alloc] init];
            NSDictionary *parentCatDic = [jiancaiDic objectForKey:@"parentCat"];
            classD.name = [parentCatDic objectForKey:@"cat_name"];
            classD.subCatArr = [NSMutableArray array];
            NSArray *subCatArr = [jiancaiDic objectForKey:@"subCatList"];
            for (NSDictionary *dic in subCatArr) {
                SubCat *subCat = [[SubCat alloc] init];
                [subCat setValuesForKeysWithDictionary:dic];
                [classD.subCatArr addObject:subCat];
            }
            [self.leftArr addObject:classD];
        }
        
        NSArray *zhuangshiArr = [rootDic objectForKey:@"zhuangshi"];

        for (NSDictionary *zhuangshiDic in zhuangshiArr) {
            ByClassData *classD = [[ByClassData alloc] init];
            NSDictionary *parentCatDic = [zhuangshiDic objectForKey:@"parentCat"];
            classD.name = [parentCatDic objectForKey:@"cat_name"];
            classD.subCatArr = [NSMutableArray array];
            NSArray *subCatArr = [zhuangshiDic objectForKey:@"subCatList"];
            for (NSDictionary *dic in subCatArr) {
                SubCat *subCat = [[SubCat alloc] init];
                [subCat setValuesForKeysWithDictionary:dic];
                [classD.subCatArr addObject:subCat];
            }
            [self.leftArr addObject:classD];
        }

        
        ByClassData *tempClassD = [self.leftArr firstObject];
        self.rightArr = tempClassD.subCatArr;
        self.selectName = @"卧室";
        [_collectionV reloadData];
        [_tableV reloadData];
        
        // 处理完数据把第一个cell名变红色
        for (ByClassTableViewCell *cell in self.tableV.visibleCells)
        {
            cell.nameL.textColor = [UIColor blackColor];
            cell.redV.hidden = YES;
            
            if ([cell.nameL.text isEqualToString:self.selectName]) {
                
                cell.nameL.textColor = [UIColor redColor];
                cell.redV.hidden = NO;
            }else
            {
                cell.nameL.textColor = [UIColor blackColor];
                cell.redV.hidden = YES;
            }
        }
        
//        [self.tableV selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
